<template>
  <div class="pdf-viewer-container">
    <div v-if="loading" class="loading-container">
      <Loader class="loading-icon" />
      <p>PDF 加载中，请稍候...</p>
    </div>

    <div v-else-if="loadError" class="error-container">
      <AlertCircle size="48" />
      <p>{{ loadError }}</p>
      <button class="error-action" @click="reloadPdf">重试</button>
    </div>

    <vue-pdf-embed
      v-else
      class="pdf-viewer"
      :source="pdfSource"
      :page="currentPage"
      :rotation="rotation"
      :scale="scale"
      @rendered="onPdfRendered"
      @loading="setLoading(true)"
      @loaded="onPdfLoaded"
      @error="onPdfError"
    />

    <div class="toolbar">
      <button :disabled="currentPage <= 1" title="上一页" @click="prevPage">
        <ChevronLeft />
      </button>
      <span class="page-info">{{ currentPage }} / {{ totalPages }}</span>
      <button :disabled="currentPage >= totalPages" title="下一页" @click="nextPage">
        <ChevronRight />
      </button>
      <div class="separator"></div>
      <button title="缩小" @click="zoomOut">
        <Minus />
      </button>
      <button title="放大" @click="zoomIn">
        <Plus />
      </button>
      <div class="separator"></div>
      <button title="逆时针旋转" @click="rotateLeft">
        <RotateCcw />
      </button>
      <button title="顺时针旋转" @click="rotateRight">
        <RotateCw />
      </button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, defineProps, defineEmits } from 'vue'
import VuePdfEmbed from 'vue-pdf-embed'
import {
  ChevronLeft,
  ChevronRight,
  Plus,
  Minus,
  RotateCcw,
  RotateCw,
  Loader,
  AlertCircle
} from 'lucide-vue-next'

const props = defineProps({
  filePath: {
    type: String,
    required: true
  }
})

const emit = defineEmits(['loading-change'])

// 状态变量
const currentPage = ref(1)
const totalPages = ref(1)
const scale = ref(1.0)
const rotation = ref(0)
const loading = ref(true)
const loadError = ref('')
const pdfSource = ref('')

// 计算PDF源
onMounted(() => {
  if (props.filePath) {
    // 处理不同的文件路径格式
    if (props.filePath.startsWith('file://')) {
      // 已经是file://格式
      pdfSource.value = props.filePath
    } else if (props.filePath.startsWith('http://') || props.filePath.startsWith('https://')) {
      // 远程URL
      pdfSource.value = props.filePath
    } else {
      // 本地文件路径
      pdfSource.value = `file://${props.filePath}`
    }

    console.log('PDF源路径:', pdfSource.value)
  } else {
    loadError.value = '未提供文件路径'
    loading.value = false
  }
})

// PDF事件处理
const onPdfLoaded = (numPages: number): void => {
  loading.value = false
  totalPages.value = numPages
  emit('loading-change', false)
}

const onPdfRendered = (): void => {
  loading.value = false
  emit('loading-change', false)
}

const onPdfError = (error: Error | unknown): void => {
  loading.value = false
  loadError.value = `PDF加载失败: ${error instanceof Error ? error.message : '未知错误'}`
  console.error('PDF加载错误:', error)
  emit('loading-change', false)
}

// 设置加载状态
const setLoading = (status: boolean): void => {
  loading.value = status
  emit('loading-change', status)
}

// 导航和控制方法
const nextPage = (): void => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++
    setLoading(true)
  }
}

const prevPage = (): void => {
  if (currentPage.value > 1) {
    currentPage.value--
    setLoading(true)
  }
}

const zoomIn = (): void => {
  scale.value = Math.min(scale.value + 0.1, 3)
}

const zoomOut = (): void => {
  scale.value = Math.max(scale.value - 0.1, 0.5)
}

const rotateLeft = (): void => {
  rotation.value = (rotation.value - 90) % 360
}

const rotateRight = (): void => {
  rotation.value = (rotation.value + 90) % 360
}

const reloadPdf = (): void => {
  loadError.value = ''
  loading.value = true
  emit('loading-change', true)

  console.log('重新加载PDF:', props.filePath)

  // 重新设置PDF源以触发重新加载
  const currentSource = pdfSource.value
  pdfSource.value = ''

  setTimeout(() => {
    // 重新计算PDF源路径
    if (props.filePath) {
      if (props.filePath.startsWith('file://')) {
        pdfSource.value = props.filePath
      } else if (props.filePath.startsWith('http://') || props.filePath.startsWith('https://')) {
        pdfSource.value = props.filePath
      } else {
        pdfSource.value = `file://${props.filePath}`
      }
      console.log('重试加载PDF源:', pdfSource.value)
    } else {
      pdfSource.value = currentSource
    }
  }, 100)
}
</script>

<style scoped>
.pdf-viewer-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  position: relative;
}

.pdf-viewer {
  flex: 1;
  min-height: 0;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  background-color: white;
}

.toolbar {
  display: flex;
  align-items: center;
  padding: 8px 16px;
  background-color: var(--theme-bg-primary);
  border-top: 1px solid var(--theme-border-light);
  gap: 8px;
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 10;
  backdrop-filter: blur(10px);
  background-color: rgba(255, 255, 255, 0.9);
}

.toolbar button {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 36px;
  height: 36px;
  border-radius: 4px;
  background-color: transparent;
  border: 1px solid var(--theme-border-light);
  color: var(--theme-text-secondary);
  cursor: pointer;
  transition: all 0.2s ease;
}

.toolbar button:hover:not(:disabled) {
  background-color: var(--theme-bg-tertiary);
  color: var(--theme-primary);
}

.toolbar button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-info {
  font-size: 14px;
  color: var(--theme-text-secondary);
  margin: 0 4px;
}

.separator {
  width: 1px;
  height: 24px;
  background-color: var(--theme-border-light);
  margin: 0 8px;
}

.loading-container,
.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  gap: 16px;
  color: var(--theme-text-secondary);
}

.loading-icon {
  animation: spin 1.5s linear infinite;
}

.error-action {
  padding: 8px 16px;
  background-color: var(--theme-primary);
  color: white;
  border: none;
  border-radius: 4px;
  font-weight: 500;
  cursor: pointer;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
